package org.jeecg.modules.mes.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.mes.order.entity.*;
import org.jeecg.modules.mes.order.mapper.MesSaleItemMapper;
import org.jeecg.modules.mes.order.mapper.MesOrderSaleMapper;
import org.jeecg.modules.mes.order.service.IExpApplyBillService;
import org.jeecg.modules.mes.order.service.IExpApplyMainService;
import org.jeecg.modules.mes.order.service.IMesOrderSaleService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 订单管理—销售订单
 * @Author: jeecg-boot
 * @Date:   2020-10-19
 * @Version: V1.0
 */
@Service
public class MesOrderSaleServiceImpl extends ServiceImpl<MesOrderSaleMapper, MesOrderSale> implements IMesOrderSaleService {

	@Autowired
	private MesOrderSaleMapper mesOrderSaleMapper;
	@Autowired
	private MesSaleItemMapper mesSaleItemMapper;

	@Autowired
	private IExpApplyBillService expApplyBillService;
	@Autowired
	private IExpApplyMainService expApplyMainService;

	@Override
	@Transactional
	public void delMain(String id) {
		mesSaleItemMapper.deleteByMainId(id);
		mesOrderSaleMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			mesSaleItemMapper.deleteByMainId(id.toString());
			mesOrderSaleMapper.deleteById(id);
		}
	}
	@Override
	@Transactional
	public void saveExpUpdateState(MesOrderSale sale, List<ExpApplyBill> bills){
		//判断主表是否有该数据
		QueryWrapper<ExpApplyMain> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("sale_id",sale.getId());
		ExpApplyMain expmain = expApplyMainService.getOne(queryWrapper);

		ExpApplyMain expApplyMain = new ExpApplyMain();
		if(expmain==null){
			expApplyMain.setSaleId(sale.getId());
			expApplyMain.setOrderName(sale.getOrderName());
			expApplyMain.setOrderCode(sale.getOrderCode());
			expApplyMain.setOrderType(sale.getOrderType());
			expApplyMain.setGrossPrice(sale.getGrossPrice());
			expApplyMain.setCurrency(sale.getCurrency());
			expApplyMain.setState("未上传");
			expApplyMainService.save(expApplyMain);
		}else {
			expApplyMain.setId(expmain.getId());
		}
		//修改销售订单状态
		mesOrderSaleMapper.updateById(sale);
		for(ExpApplyBill bill:bills) {
			bill.setExpMainId(expApplyMain.getId());
//			QueryWrapper<ExpApplyBill> queryWrapper1 = new QueryWrapper<>();
//			queryWrapper1.eq("exp_apply_main",expApplyMain.getId());
//			queryWrapper1.eq("material",bill.getMaterial());
//			List<ExpApplyBill> list = expApplyBillService.list(queryWrapper1);
//			if(list.size()==0) {
				expApplyBillService.save(bill);
//			}
		}
	}
	
}
